import { useCallback, useEffect, useState } from 'react';
import { Select, Empty, Spin } from 'antd';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
import { cloneDeep } from 'lodash';
import { getMessage } from '@inbiz/react';
import useDebounce from './hook';
import { getColumnList } from './service';
import './index.less';

const MultiSelect = (props: {
  value?: string[];
  onChange?: Function;
  option: string[];
  name: string;
  outId: string;
}) => {
  // 当前选中值
  const [selectValue, $selectValue] = useState<string[]>([]);
  // 当前可选值
  const [option, $option] = useState<string[]>([]);
  // 搜索值
  const [search, $search] = useState<string>('');
  // 搜索请求loading
  const [searchLoading, $searchLoading] = useState<boolean>(false);
  // 追加option
  const [addOption, $addOption] = useState<string[]>([]);

  // 防抖后的搜索值
  const searchTxt = useDebounce(search, 100);

  // 初始化回显值
  useEffect(() => {
    if (Array.isArray(props.value)) {
      $selectValue(cloneDeep(props.value));
    }
  }, [props.value]);

  // 监听防抖后的搜索值变化-查询数据
  useEffect(() => {
    if (typeof searchTxt === 'string' && searchTxt !== '') {
      searchData(searchTxt);
    } else {
      if (Array.isArray(props.option)) {
        $addOption((pre) => {
          let arr = addOption;
          arr = cloneDeep(pre);
          $option([...cloneDeep(props.option), ...arr]);
          return pre;
        });
      }
    }
  }, [searchTxt]);

  // 搜索
  const searchData = async (text: string) => {
    $searchLoading(true);
    let params = {
      soureOutId: props.outId,
      columnName: props.name,
      keyWork: text,
    };
    let res = await getColumnList(params);
    if (Array.isArray(res)) {
      $option(res);
    }
    $searchLoading(false);
  };

  // 删除选中
  const delItem = useCallback(
    (val: string) => {
      let arr = selectValue.filter((item: string) => item !== val);
      props?.onChange?.(arr);
    },
    [selectValue],
  );

  // 选中
  const pickItem = useCallback(
    (val: string) => {
      let arr = cloneDeep(selectValue);
      if (arr.includes(val)) {
        // 已选择，删除
        let arr1 = arr.filter((item: string) => item !== val);
        props?.onChange?.(arr1);
      } else {
        // 未选择，添加
        arr.push(val);
        props?.onChange?.(arr);
        let opt = cloneDeep(props.option);
        if (!opt.includes(val)) {
          $addOption((pre) => {
            let arr = [...pre, val];
            return arr;
          });
        }
      }
    },
    [selectValue, props.option],
  );

  return (
    <div className={'multiselect-nav'}>
      <Select
        value={null}
        showSearch
        placeholder={getMessage('BiFilterModal.placeHolder_please_select')} // 请选择
        // allowClear
        // onClear={() => {
        //   // 清空搜索值回显所有可选项（延迟执行避免屏闪）
        //   let timer = setTimeout(() => {
        //     $search('');
        //     clearTimeout(timer);
        //   }, 200);
        // }}
        onInputKeyDown={(e) => {
          // 回车触发搜索
          if (e.key === 'Enter') {
            let target: any = e.target;
            $search(target.value?.trim() || '');
          }
        }}
        onSearch={(val: string) => {
          // 删空搜索值回显所有可选项
          if (val === '') {
            $search(val);
          }
        }}
        dropdownClassName={'bi-filter-item-select'}
        dropdownRender={() => {
          return (
            <Spin spinning={searchLoading}>
              <ul>
                {option.length ? (
                  option.map((item: string) => {
                    return (
                      <li
                        key={item}
                        className={
                          selectValue.includes(item)
                            ? `${'option-item'} ${'option-item-active'}`
                            : 'option-item'
                        }
                        onClick={() => pickItem(item)}
                      >
                        {item}
                        {selectValue.includes(item) && (
                          <CheckOutlined style={{ color: '#1890fa' }} />
                        )}
                      </li>
                    );
                  })
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
              </ul>
            </Spin>
          );
        }}
      >
        <Select.Option value="1" key="1">
          '1'
        </Select.Option>
      </Select>
      {Array.isArray(selectValue) && selectValue.length ? (
        <div className={'selected-list'}>
          {selectValue.map((item: string) => {
            return (
              <div key={item} className={'selected-list-item'}>
                <span>{item}</span>
                <span className={'clone-btn'} onClick={() => delItem(item)}>
                  <CloseOutlined />
                </span>
              </div>
            );
          })}
        </div>
      ) : null}
    </div>
  );
};

export default MultiSelect;
